package com.rh.filter;
import com.rh.entity.SecurityUser;
import com.rh.entity.User;
import com.rh.security.TokenManager;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rh.result.ResultVo;
import com.rh.utils.ResponseUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
/**
 * 认证过滤器，继承UsernamePasswordAuthenticationFilter，对用户名密码进行登录校验,
 *
 */
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {
    //引入SpringSecurity权限管理器
    private AuthenticationManager authenticationManager;
    //引入自定义Token管理器
    private TokenManager tokenManager;
    //引入Redis模板
    private RedisTemplate redisTemplate;

    //有参构造方法
    public TokenLoginFilter(AuthenticationManager authenticationManager, TokenManager tokenManager, RedisTemplate redisTemplate) {
        this.authenticationManager = authenticationManager;
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
        //设置两个额外属性
        //1.设置非仅Post提交
        this.setPostOnly(false);
        //2.设置当前登陆的请求地址
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/admin/acl/login","POST"));
    }
    /**
     * 获取用户名和密码的方法
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
            throws AuthenticationException {
        try {
            //创建一个ObjectMapper对象,使用readValue方法传一个输入流和用户实体类的Class对象
            User user = new ObjectMapper().readValue(req.getInputStream(), User.class);
            //返回authenticate对象，传用户名、密码、权限列表
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), new ArrayList<>()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 认证成功的方法
     */
    @Override
    protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain,
                                            Authentication auth) throws IOException, ServletException {
        SecurityUser user = (SecurityUser) auth.getPrincipal();
        //生成token值并做返回
        String token = tokenManager.createToken(user.getCurrentUserInfo().getUsername());
        //登陆成功之后把用户名和权限列表放到Redis中
        redisTemplate.opsForValue().set(user.getCurrentUserInfo().getUsername(), user.getPermissionValueList());
        ResponseUtil.out(res, ResultVo.ok().data("token", token));
    }
    /**
     * 认证失败的方法
     */
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                                              AuthenticationException e) throws IOException, ServletException {
        ResponseUtil.out(response, ResultVo.error().message("用户名或者密码不正确!"));
    }
}
